﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RTracker.Models.Common;
using RTracker.Models.User;
using System.Web.Services;

namespace RTracker.Controllers
{
    public class UserController : AppBaseController
    {
        //
        // GET: /User/

        [HttpPost]
        public ActionResult Save(GUser oGUser)
        {
            try
            {
                //check if Model validation is true if not then return detail view with errors
                if (true)//ModelState.IsValid
                {
                    //call CheckSession to get session status
                    string SessionState = CheckSessionState();
                    //check if session state is ok else return false status to view.
                    if (SessionState == CAppConstants.SessionSuccess)
                    {
                        bool _userPermission = false;

                        if (oGUser.User.OrganizationId == 0)
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationCreate);
                        }
                        else
                        {
                            _userPermission = checkUserPermission(CUserPermissionsConstants.OrganizationUpdate);
                        }


                        if (_userPermission)
                        {
                            CUser objCUser = new CUser();
                            objCUser = oGUser.User;
                            MUser objMUser = new MUser();

                            if (objCUser.UserId == 0)
                            {
                                objCUser.OrganizationId = CurrentUserSession.OrganizationId;
                                oGUser.Status = objMUser.CreateUser(AuthenticationContext, ref objCUser);
                            }
                            else
                            {
                                oGUser.Status = objMUser.UpdateUser(AuthenticationContext, ref objCUser);
                            }
                        }
                        else
                        {
                            oGUser.Status = new CStatus();
                            oGUser.Status.Success = false;
                            oGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        oGUser.Status = new CStatus();
                        oGUser.Status.Success = false;
                        oGUser.Status.StatusDetails = SessionState;
                    }
                }
                else
                {
                    oGUser.Status = new CStatus();
                    oGUser.Status.Success = false;
                    oGUser.Status.StatusDetails = CAppErrorsConstants.ValidationFail;
                }
            }
            catch (Exception ex)
            {
                oGUser.Status = new CStatus();
                oGUser.Status.Success = false;
                oGUser.Status.StatusDetails = ex.Message;
            }
            return Json(oGUser);
        }

        [HttpPost]
        public ActionResult GetDetails(int pnId)
        {
            GUser objGUser = new GUser();

            objGUser.Status = new CStatus();

            objGUser.User = new CUser();

            objGUser.User.UserId = pnId;

            CUser objCuser = new CUser();

            ViewBag.IsDisabled = true;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationCreate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGUser.Status.Success = true;
                            objGUser.Status.StatusDetails = CAppConstants.DetailSuccess;
                        }
                        else
                        {
                            objGUser.Status.Success = false;
                            objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDetailView))
                        {
                            //here we will append new for detail 
                            MUser objMUser = new MUser();

                            ViewBag.IsNew = false;

                            objCuser.UserId = objGUser.User.UserId;

                            objGUser.Status = objMUser.GetUserDetail(AuthenticationContext, ref objCuser);

                            //get the different admin names from their id from the application user list
                            objCuser.CreatedByName = GetFullName(objCuser.CreatedBy);
                            objCuser.ModifiedByName = GetFullName(objCuser.ModifiedBy);
                            objCuser.SoftLockedByName = GetFullName(objCuser.SoftLockedBy);
                            objCuser.HardLockedByName = GetFullName(objCuser.HardLockedBy);


                            if (!CheckLocksByOther(objCuser))
                            {
                                ViewBag.IsDisabled = false;
                            }
                            if (objGUser.Status.Success == true)
                            {
                                objGUser.User = objCuser;
                            }
                        }
                        else
                        {
                            objGUser.Status = new CStatus();
                            objGUser.Status.Success = false;
                            objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                }
                else
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }

            return PartialView("_detail", objGUser);
        }

        [HttpPost]
        public ActionResult DeleteRecords(string pstrIds)
        {
            GUser objGUser = new GUser();

            objGUser.User = new CUser();

            objGUser.User.UserIds = pstrIds;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (pstrIds != "")
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationDelete))
                        {
                            //code to delete the record
                            MUser objMUser = new MUser();

                            CUser objCuser = new CUser();

                            objCuser.UserIds = objGUser.User.UserIds;

                            objGUser.Status = objMUser.DeleteUser(AuthenticationContext, ref objCuser);

                            if (objGUser.Status.Success == true)
                            {
                                objGUser.User = objCuser;
                            }
                        }
                        else
                        {
                            objGUser.Status = new CStatus();
                            objGUser.Status.Success = false;
                            objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        objGUser.Status = new CStatus();
                        objGUser.Status.Success = false;
                        objGUser.Status.StatusDetails = CAppErrorsConstants.NotValidRequest;
                    }
                }
                else
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }

            return Json(objGUser.Status);
        }       

        [HttpPost]
        public ActionResult GridRefresh(int pnId, string pstrSortOn, string pstrSortType, int pnPageNo, int pnPageSize, string pstrSearch, string pstrSearchOn, int pnOrgId = 1)
        {

            GUser objGUser = new GUser();
            try
            {
                if (pstrSearch == null || pstrSearchOn == null)
                {
                    pstrSearch = "";
                    pstrSearchOn = "";
                }

                //call CheckSession to get session status
                string SessionState = CheckSessionState();

                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {
                    CUser objCUser = new CUser() { UserId = pnId, SortOn = pstrSortOn, SortType = pstrSortType, PageNumber = pnPageNo,RowSize = pnPageSize, Search = pstrSearch, SearchOn = pstrSearchOn, OrganizationId = pnOrgId };


                    //check if current users organization id is 1 then it means it is superUser then need to get all organizations list
                    if (CurrentUserSession.OrganizationId == pnOrgId)
                    {

                        MUser objMUser = new MUser();

                        objGUser = objMUser.GetUserGridList(objCUser, AuthenticationContext);

                        if (objGUser.LstUser != null)
                        {
                            if (objGUser.LstUser.Count > 0)
                            {
                                objGUser.LstUser.ForEach(user =>
                                {
                                    user.CreatedByName = GetFullName(user.CreatedBy);
                                    user.ModifiedByName = GetFullName(user.ModifiedBy);
                                    user.SoftLockedByName = GetFullName(user.SoftLockedBy);
                                    user.HardLockedByName = GetFullName(user.HardLockedBy);
                                });
                            }
                        }

                        // if status is true get object of the record to be selected in the list.
                        // first of all we will check the if given record exist in the list.
                        // if given record exist then get the object of that record.
                        // if record not exist in the list then select the first record of the list.
                        if (objGUser.Status.Success)
                        {
                            // if status is true get object of the record to be selected in the list.
                            // first of all we will check the if given record exist in the list.
                            // if given record exist then get the object of that record.
                            // if record not exist in the list then select the first record of the list.
                            if (objGUser.LstUser != null)
                            {
                                CUser objSelectedCUser = objGUser.LstUser.Where(m => m.UserId == pnId).DefaultIfEmpty(objGUser.LstUser[0]).First();

                                // check if record is not already hard locked or softlocked
                                if (objSelectedCUser.IsSoftLocked == false && objSelectedCUser.IsHardLocked == false)
                                {
                                    objSelectedCUser.CreatedBy = CurrentUserSession.UserId;
                                    objGUser.Status = objMUser.SetUserSoftLock(AuthenticationContext, objSelectedCUser);
                                    if (objGUser.Status.Success)
                                    {
                                        // updating the list with softlock details
                                        objGUser.LstUser.Where(m => m.UserId == objSelectedCUser.UserId).First().IsSoftLocked = true;
                                        objGUser.LstUser.Where(m => m.UserId == objSelectedCUser.UserId).First().SoftLockedBy = CurrentUserSession.UserId;
                                    }
                                }
                            }


                        }

                        ViewBag.bPagingEnabled = true;
                        ViewBag.bSearchEnabled = true;
                        ViewBag.bNewDeleteEnabled = true;
                        ViewBag.bCopyPasteEnabled = false;
                    }
                    //else get detail for current users organization and show it in grid.
                    else
                    {
                        objCUser = new CUser() { OrganizationId = CurrentUserSession.OrganizationId };

                        MUser objMUser = new MUser();

                        objGUser.Status = objMUser.GetUserDetail(AuthenticationContext, ref objCUser);

                        objGUser.LstUser.Add(objCUser);
                        //set view bag variables for pagging, new, delete and search.
                        ViewBag.bPagingEnabled = false;
                        ViewBag.bSearchEnabled = false;
                        ViewBag.bNewDeleteEnabled = false;
                        ViewBag.bCopyPasteEnabled = false;
                    }

                    // check if status is true
                    if (objGUser.Status.Success)
                    {
                        if (objGUser.LstUser != null)
                        {
                            if (objGUser.LstUser.Count > 0)
                            {
                                objGUser.LstUser[0].SortOn = pstrSortOn;
                                objGUser.LstUser[0].SortType = pstrSortType;
                            }
                        }
                        // set the values of sort on and sort type in the view bag.
                        ViewBag.SortType = pstrSortType;
                        ViewBag.SortOn = pstrSortOn;
                        ViewBag.CurrentUser = CurrentUserSession.UserId;
                    }
                }
                else
                {
                    //set status to false and its detail.
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {
                // catch the exceptions in any step ,if any 
                //set status to false and its detail as exception message.
                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }
            ViewBag.CurrentUser = CurrentUserSession.UserId;
            //check if status is true then return list view(partial view of list) else return object with false status.
            if (objGUser.Status.Success)
                return PartialView("_list", objGUser);
            else
                return Json(objGUser);
        }

        [HttpPost]
        public ActionResult ReleaseSoftLock(int pnId)
        {
            GUser objGUser = new GUser();

            objGUser.User = new CUser();

            objGUser.User.UserId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    //check if Id param is 0 means new is clicked then set selected row object to new.
                    if (0 == pnId)
                    {
                        if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                        {
                            //here we will append new form to create new organisation
                            ViewBag.IsNew = true;
                            objGUser.Status.Success = true;
                        }
                        else
                        {
                            objGUser.Status.Success = false;
                            objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                        }
                    }
                    else
                    {
                        MUser objMUser = new MUser();
                        objGUser.User.CreatedBy = CurrentUserSession.UserId;
                        objGUser.Status = objMUser.ReleaseUserSoftLock(AuthenticationContext, objGUser.User);
                    }
                }
                else
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }

            return Json(objGUser.Status);
        }

        [HttpPost]
        public ActionResult SetHardLock(int pnId)
        {
            GUser objGUser = new GUser();

            objGUser.User = new CUser();

            objGUser.User.UserId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    ////check if Id param is 0 means new is clicked then set selected row object to new.
                    //if (0 == pnId)
                    //{
                    //    if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                    //    {
                    //        //here we will append new form to create new organisation
                    //        ViewBag.IsNew = true;
                    //        objGUser.Status.Success = true;
                    //    }
                    //    else
                    //    {
                    //        objGUser.Status.Success = false;
                    //        objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                    //    }
                    //}
                    //else
                    //{
                    MUser objMUser = new MUser();
                    objGUser.User.CreatedBy = CurrentUserSession.UserId;
                    objGUser.Status = objMUser.SetUserHardLock(AuthenticationContext, objGUser.User);
                    //}
                }
                else
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }

            return Json(objGUser.Status);
        }

        [HttpPost]
        public ActionResult ReleaseHardLock(int pnId)
        {
            GUser objGUser = new GUser();

            objGUser.User = new CUser();

            objGUser.User.UserId = pnId;
            try
            {
                //call CheckSession to get session status
                string SessionState = CheckSessionState();
                //IsDisabled checks whether cureently selected row is hardlocked or softlocked by other
                ViewBag.IsDisabled = true;
                ViewBag.IsNew = false;
                //check if session state is ok else return false status to view.
                if (SessionState == CAppConstants.SessionSuccess)
                {

                    ////check if Id param is 0 means new is clicked then set selected row object to new.
                    //if (0 == pnId)
                    //{
                    //    if (checkUserPermission(CUserPermissionsConstants.OrganizationUpdate))
                    //    {
                    //        //here we will append new form to create new organisation
                    //        ViewBag.IsNew = true;
                    //        objGUser.Status.Success = true;
                    //    }
                    //    else
                    //    {
                    //        objGUser.Status.Success = false;
                    //        objGUser.Status.StatusDetails = CAppErrorsConstants.NoPermission;
                    //    }
                    //}
                    //else
                    //{
                    MUser objMUser = new MUser();
                    objGUser.User.CreatedBy = CurrentUserSession.UserId;
                    objGUser.Status = objMUser.ReleaseUserHardLock(AuthenticationContext, objGUser.User);
                    //}
                }
                else
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = SessionState;
                }
            }
            catch (Exception ex)
            {

                objGUser.Status = new CStatus();
                objGUser.Status.Success = false;
                objGUser.Status.StatusDetails = ex.Message;
            }

            return Json(objGUser.Status);
        }

    }
}
